package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //向微信服务器请求openid和session_key
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        String response = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        if(response.contains("err")) { //微信服务器返回错误信息，登录失败
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        JSONObject jsonObject = JSONObject.parseObject(response);//解析json字符串转换为JSONObject
        String openid = jsonObject.getString("openid");

        //查找openid对象用户，如果有返回user，如果没有新增用户返回user
        User user=userMapper.selectByOpenid(openid);
        if(user==null) {//这是个新用户
            user=new User();
            user.setCreateTime(LocalDateTime.now());
            user.setOpenid(openid);
            userMapper.insertUser(user);
        }
        return user;
    }
}
